import bluebird from 'bluebird';
import db from '../db';
import * as util from '../../../util/index';

const userColumn = 'id,username,name,userType,code,mobile,createTime,institutionId';
const userColumns = userColumn.split(',');
export function fetch(query, op, pageOpt) {
    return db.get('xp_policy').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        qb.orderBy('createTime', 'desc');
    }).fetchPage({
        pageSize: pageOpt.pageSize,
        page: pageOpt.page,
        withRelated: [{
            salesman: qb => {
                qb.columns(userColumns);
            }
        },
            'salesman.institution',
            'activity',
            'activity.institution',
        ]
    });
}
export function find(query, op) {
    return db.get('xp_policy').query(qb => {
        if (query) {
            util.andWhere(query, op, qb);
        }
        qb.orderBy('createTime', 'desc');
    }).list({
        withRelated: [{
            salesman: qb => {
                qb.columns(userColumns);
            }
        },
            'salesman.institution',
            'activity',
            'activity.institution'
        ]
    });
}

export function add(policys, activity) {
    return db.exec(model =>
        bluebird.all(policys.map(i => model('xp_policy').forge().save(i, {method: 'insert'})))
            .then(() => model('xp_activity').forge().save(activity, {method: 'update', require: false})));
}
export function edit(data, activity) {
    return db.exec(model => model('xp_policy').where({id: data.id}).save(data, {method: 'update'})
        .then(() => model('xp_activity').forge().save(activity, {method: 'update', require: false})));
}
export function del(id, activity) {
    return db.exec(model => model('xp_policy').forge({id}).drop()
        .then(() => model('xp_activity').forge().save(activity, {method: 'update', require: false})));
}
